<?php
/**
*
* @package acp
* @version $Id: functions_databasepro.php 9441 2009-04-12 13:21:25Z mikovchain $
* @copyright (c) 2009 phpBB China Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

//Initialize backup process
function dbpro_initialize($module){
	global $phpbb_root_path, $phpEx, $db, $user, $cache, $config;

	$input['tablename'] = request_var('table_name', array('' => ''));
	$input['baktype'] = request_var('baktype', 0);
	$input['filesize'] = request_var('filesize', 0);
	$input['bakline'] = request_var('bakline', 0);
	$input['autoauf'] = request_var('autoauf', 0);
	$input['bakstru'] = request_var('bakstru', 0);
	$input['bakstrufour'] = request_var('bakstrufour', 0);
	$input['beover'] = request_var('beover', 0);
	$input['waitbaktime'] = request_var('waitbaktime', 0);
	$input['mypath'] = request_var('mypath', '');
	$input['insertf'] = request_var('insertf', 'insert');
	$input['dbchar'] = request_var('dbchar', '');
	$input['readme'] = utf8_normalize_nfc(request_var('readme', '', true));
	$input['autofield'] = request_var('autofield', '');
	
	if (!sizeof($input['tablename']))
	{
		trigger_error($user->lang['TABLE_SELECT_ERROR'] . adm_back_link($module->u_action), E_USER_WARNING);
	}

	if((!$input['filesize'] && $input['baktype'] == 0) || (!$input['bakline'] && $input['baktype'] == 1)){
		trigger_error("WRONG_PARAM_BACKUP_TYPE");
	}

	if(empty($input['mypath'])){
		$input['mypath']=$db->dbname . '_' .date("YmdHis");
	}
	//print_r($input);exit;

	$backup_path = $phpbb_root_path . 'store/' . $input['mypath'];
    mkdeepdir($backup_path);
    
	$readme_file = $backup_path . '/readme.txt';
	$string = $input['readme'] . "\r\n\r\nBackup Time: " . date("Y-m-d H:i:s");
	write_file_raw($readme_file, $string);

	$d_table="";
	$count=count($input['tablename']);
	for($i=0;$i<$count;$i++){
		$d_table .= '$tb[\'' . $input['tablename'][$i]. "']=0;\r\n";
    }
   
    $input['insertf'] = ($input['insertf'] == 'insert') ? 'insert' : 'replace';

	if (version_compare($db->sql_server_info(true), '4.1.0', '<') && $input['dbchar']=='auto') {
		$input['dbchar']='';
	}

	$string='<?php
$b_table="' . implode(',', $input['tablename']). '";
' . $d_table. '
$b_baktype=' . $input['baktype'] . ';
$b_filesize=' . $input['filesize'] . ';
$b_bakline=' . $input['bakline'] . ';
$b_autoauf=' . $input['autoauf'] . ';
$b_dbname="' . $db->dbname . '";
$b_stru=' . $input['bakstru'] . ';
$b_strufour=' . $input['bakstrufour'] . ';
$b_dbchar="' . addslashes($input['dbchar']) . '";
$b_beover=' . $input['beover'] . ';
$b_insertf="' . addslashes($input['insertf']) . '";
$b_autofield=",' . addslashes($input['autofield']) . '";
?>';

	$config_file = $backup_path . '/config.php';
	write_file_raw($config_file, $string);

	if($input['baktype'] == 0){
		$trunk = 'bysize';
	}
	else{
		$trunk='byvolumn';
	}
	$u_next = $module->u_action . '&amp;action=process&amp;trunk=' . $trunk . '&amp;t=0&amp;s=0&amp;p=0&amp;stime=' . time() . '&amp;mypath=' . $input['mypath'] . '&amp;waitbaktime=' . $input['waitbaktime'];
	meta_refresh($input['waitbaktime'], $u_next);
	trigger_error($user->lang['INITIALIZE_COMPLETED'] . '<br /><br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
}



function dbpro_process_bysize($module){
	global $phpbb_root_path, $phpEx, $db, $user, $cache, $config;
	
	$input['mypath']	= request_var('mypath', '');
	$input['collation']	=	request_var('collation', '');
	$input['t']		= request_var('t', 0);
	$input['s']		= request_var('s', 0);
	$input['p']	= request_var('p', 0);
	$input['waitbaktime']	= request_var('waitbaktime', 0);
	$input['alltotal']	= request_var('alltotal', 0);
	$input['thenof']	= request_var('thenof', 0);
	$input['fnum']		= request_var('fnum', 0);
	$input['stime']		= request_var('stime', 0);

	$backup_path = $phpbb_root_path . 'store/' . $input['mypath'];
	@include($backup_path."/config.php");

	if(empty($b_table)){
		trigger_error($user->lang['GENERAL_ERROR'] . adm_back_link($module->u_action), E_USER_WARNING);
	}

	if($input['stime'] == 0) {
		$stime=time();
	}

	$header='<?php
defined(\'IN_PHPBB\') or die(\'Restricted access\');
$sql = array();

';
	$footer='
?>';

	$tables=explode(",",$b_table);
	$count=count($tables);

	//When backup is ready
	if($input['t'] >= $count) {
		$message = $user->lang['BACKUP_COMPLETED_BY_TIME'] . time_spended($input['stime']);
		trigger_error($message . '<br /><br /><a href="' . $module->u_action . '"> ' . $user->lang['BACK_TO_PREV'] . '</a>');
    }
	$dumpsql = '';

	// Charset
	if($b_dbchar=='auto') {
		if($input['s'] == 0) {
			$status_r = get_table_info($tables[$input['t']]);
			$collation = get_table_charset($status_r['Collation']);
			@mysql_query("set names '".$collation."';");
			$num = $status_r['Rows'];
		} else {
			$collation = $input['collation']	;
			@mysql_query("set names '".$collation."';");
			$num = $input['alltotal'];
		}
		if($collation != '') {
			$dumpsql .= "@mysql_query(\"set names '".$collation."';\");\r\n";
		}
	} else {
		if ($b_dbchar !='') {@mysql_query("set names '".$b_dbchar."';");}
		if($input['s'] == 0) {
			$status_r = get_table_info($tables[$input['t']]);
			$num=$status_r['Rows'];
		} else {
			$num = $input['alltotal'];
		}
	}

	// Structure
	if($b_stru && $input['s'] == 0) {
		$dumpsql .= get_table_structure($tables[$input['t']], $b_strufour);
	}

	// Get fields
	if($input['fnum'] == 0) {
		$return_fr = get_table_autoincr_fields($tables[$input['t']], $b_autofield);
		$fieldnum=$return_fr['num'];
		$noautof=$return_fr['autof'];
	} else {
		$fieldnum = $input['fnum'];
		$noautof = $input['thenof'];
	}

	// Full insert
	$inf='';
	if($b_beover==1) {
		$inf='(' . get_table_fields($tables[$input['t']]).')';
	}

	$sql = 'select * from `' . $tables[$input['t']] . '` limit ' . $input['s'] . ',' . $num;
	$result = $db->sql_query($sql);
	$b=0;
	while ($row = $db->sql_fetchrow($result))
	{
		$row = array_values($row);
		$b=1;
		$input['s']++;
		$dumpsql .= '$sql[] = "' . $b_insertf . ' into `' . $tables[$input['t']] . '`' . $inf . ' values(';
		$first=1;
		for($i=0; $i < $fieldnum; $i++) {
			if(empty($first)) {
				$dumpsql .= ',';
			} else {
				$first=0;
			}
			$myi=$i+1;
			if(!isset($row[$i])||strstr($noautof, ',' . $myi . ',')) {
				$dumpsql .= "NULL";
			} else {
				$dumpsql .= "'" . string_escape($row[$i]) . "'";
			}
		}
		$dumpsql .= ");\";\r\n";
		// Exceed limits? Dump this piece to file
		if(strlen($dumpsql)>=$b_filesize*1024) {
			$input['p']++;
			$sfile = $backup_path . '/' . $tables[$input['t']] . '_' . $input['p'] . '.php';
			$dumpsql = $header . $dumpsql . $footer;
			write_file_raw($sfile,$dumpsql);
			$db->sql_freeresult($result);

			$u_next = $module->u_action . '&amp;action=process&amp;trunk=bysize&amp;s=' . $input['s']
				 . '&amp;p=' . $input['p'] 
				 . '&amp;t=' . $input['t'] 
				 . '&amp;mypath=' . $input['mypath'] 
				 . '&amp;alltotal=' . $num 
				 . '&amp;thenof=' . $noautof 
				 . '&amp;fieldnum=' . $fieldnum 
				 . '&amp;stime=' . $input['stime'] 
				 . '&amp;waitbaktime= ' . $input['waitbaktime'] 
				 . '&amp;collation=' . $input['collation'];
			 meta_refresh($input['waitbaktime'], $u_next);
			 trigger_error($user->lang['BACKUP_STEP_COMPLETED'] . backup_progress_info($tables[$input['t']],$count,$input['t'],$num,$input['s']) . '<br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');

		}
	}
	$db->sql_freeresult($result);

	// The final piece of this table
	if($input['p'] == 0 || $b == 1)
	{
		$input['p']++;
		$sfile=$backup_path . '/' . $tables[$input['t']] . '_' . $input['p'] . '.php';
		$dumpsql = $header . $dumpsql . $footer;
		write_file_raw($sfile,$dumpsql);
	}
	update_config_filenum($input['p'], $tables[$input['t']], $backup_path);
	$input['t']++;

	$u_next = $module->u_action . '&amp;action=process&amp;trunk=bysize&amp;s=0&amp;p=0&amp;t=' . $input['t']  
		. '&amp;mypath=' . $input['mypath']  
		. '&amp;stime=' . $input['stime']  
		. '&amp;waitbaktime= ' . $input['waitbaktime'];
	meta_refresh($input['waitbaktime'], $u_next);
	trigger_error($user->lang['BACKUP_TABLE_COMPLETED'] . $tables[$input['t'] - 1] . '<br /><br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
}


function dbpro_process_byvolumn($module){
	global $phpbb_root_path, $phpEx, $db, $user, $cache, $config;

	$input['t']		= request_var('t', 0);
	$input['s']		= request_var('s', 0);
	$input['p']	= request_var('p', 0);
	$input['mypath']	= request_var('mypath', '');
	$input['alltotal']	= request_var('alltotal', 0);
	$input['thenof']	= request_var('thenof', 0);
	$input['fnum']		= request_var('fnum', 0);
	$input['auf']		= request_var('auf', '');
	$input['aufval']		= request_var('aufval', 0);
	$input['stime']		= request_var('stime', 0);
	$input['collation']	=	request_var('collation', '');
	$input['waitbaktime']	= request_var('waitbaktime', 0);

	$backup_path = $phpbb_root_path . 'store/' . $input['mypath'];

	@include($backup_path."/config.php");
	
	if(empty($b_table)){
		trigger_error($user->lang['GENERAL_ERROR'] . adm_back_link($module->u_action), E_USER_WARNING);
	}

	if($input['stime'] == 0) {
		$stime=time();
	}

	$header='<?php
defined(\'IN_PHPBB\') or die(\'Restricted access\');
$sql = array();

';
	$footer='
?>';

	$tables=explode(",",$b_table);
	$count=count($tables);

	//When backup is ready
	if($input['t'] >= $count) {
		$message = $user->lang['BACKUP_COMPLETED_BY_TIME'] . time_spended($input['stime']);
		trigger_error($message . '<br /><br /><a href="' . $module->u_action . '"> ' . $user->lang['BACK_TO_PREV'] . '</a>');
    }
	$dumpsql = '';

	// Charset
	if($b_dbchar=='auto') {
		if($input['s'] == 0) {
			$status_r = get_table_info($tables[$input['t']]);
			$collation = get_table_charset($status_r['Collation']);
			@mysql_query("set names '".$collation."';");
			$num = $status_r['Rows'];
		} else {
			$collation = $input['collation']	;
			@mysql_query("set names '".$collation."';");
			$num = $input['alltotal'];
		}
		if($collation != '') {
			$dumpsql .= "@mysql_query(\"set names '".$collation."';\");\r\n";
		}
	} else {
		if ($b_dbchar !='') {@mysql_query("set names '".$b_dbchar."';");}
		if($input['s'] == 0) {
			$status_r = get_table_info($tables[$input['t']]);
			$num=$status_r['Rows'];
		} else {
			$num = $input['alltotal'];
		}
	}

	// Structure
	if($b_stru && $input['s'] == 0) {
		$dumpsql .= get_table_structure($tables[$input['t']], $b_strufour);
	}

	// Get fields
	if($input['fnum'] == 0) {
		$return_fr = get_table_autoincr_fields($tables[$input['t']], $b_autofield);
		$fieldnum=$return_fr['num'];
		$noautof=$return_fr['autof'];
		$input['auf']=$return_fr['auf'];
	} else {
		$fieldnum = $input['fnum'];
		$noautof = $input['thenof'];
	}

	// Use the auto-increase fields
	if($b_autoauf==1 && $input['auf'] ) {
		$sql = 'select * from `' . $tables[$input['t']] . '` where ' . $input['auf'] . '>' . $input['aufval'] . ' order by ' . $input['auf'] . ' limit ' . $b_bakline;
	}
	else
	{
		$sql = 'select * from `' . $tables[$input['t']] . '` limit ' . $input['s']	 . ', ' . $b_bakline;
	}

	// Full insert
	$inf='';
	if($b_beover==1) {
		$inf='(' . get_table_fields($tables[$input['t']]).')';
	}

	$result = $db->sql_query($sql);
	$lastaufval = $b = 0;
	while ($row = $db->sql_fetchrow($result))
	{
		$rowval = array_values($row);
		if($input['auf']) {
			$lastaufval = $row[$input['auf']];
		}
		$b=1; $input['s']	++;
		$dumpsql .= '$sql[] = "' . $b_insertf . ' into `' . $tables[$input['t']] . '`' . $inf . ' values(';
		$first=1;
		for($i=0; $i < $fieldnum; $i++) {
			if(empty($first)) {
				$dumpsql.=",";
			} else {
				$first=0;
			}
			$myi=$i+1;
			if(!isset($rowval[$i])||strstr($noautof,",".$myi.",")) {
				$dumpsql .= "NULL";
			} else {
				$dumpsql .= "'" . string_escape($rowval[$i]) . "'";
			}
		}
		$dumpsql .= ");\";\r\n";
	}
	$db->sql_freeresult($result);

	if($b == 0) {
		// The final piece of this table
		if($input['p'] == 0) {
			$input['p']++;
			$sfile = $backup_path . '/' . $tables[$input['t']] . '_' . $input['p'] . '.php';
			$dumpsql = $header . $dumpsql . $footer;
			write_file_raw($sfile,$dumpsql);
		}
		update_config_filenum($input['p'], $tables[$input['t']], $backup_path);
		$input['t']++;
		$db->sql_freeresult($result);

		$u_next = $module->u_action . '&amp;action=process&amp;trunk=byvolumn&amp;s=0&amp;p=0&amp;t=' . $input['t']  
			. '&amp;mypath=' . $input['mypath']  
			. '&amp;stime=' . $input['stime']  
			. '&amp;waitbaktime= ' . $input['waitbaktime'];
		meta_refresh($input['waitbaktime'], $u_next);
		trigger_error($user->lang['BACKUP_TABLE_COMPLETED'] . $tables[$input['t'] - 1] . '<br /><br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
	}
	// Go to next piece
	$input['p']++;
	$sfile = $backup_path . '/' . $tables[$input['t']] . '_' . $input['p'] . '.php';
	$dumpsql = $header . $dumpsql . $footer;
	write_file_raw($sfile,$dumpsql);

	$u_next = $module->u_action . '&amp;action=process&amp;trunk=byvolumn&amp;s=' . $input['s']
		 . '&amp;p=' . $input['p'] 
		 . '&amp;t=' . $input['t'] 
		 . '&amp;mypath=' . $input['mypath'] 
		 . '&amp;alltotal=' . $num 
		 . '&amp;thenof=' . $noautof 
		 . '&amp;fieldnum=' . $fieldnum 
		 . '&amp;auf=' . $input['auf']
		 . '&amp;aufval=' . $lastaufval
		 . '&amp;stime=' . $input['stime'] 
		 . '&amp;waitbaktime= ' . $input['waitbaktime'] 
		 . '&amp;collation=' . $input['collation'];
	 meta_refresh($input['waitbaktime'], $u_next);
	 trigger_error($user->lang['BACKUP_STEP_COMPLETED'] . backup_progress_info($tables[$input['t']],$count,$input['t'],$num,$input['s']) . '<br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
}

function restore_from_file($module){
	global $phpbb_root_path, $phpEx, $config, $db, $user;
	
	$input['t']		= request_var('t', 0);
	$input['p']	= request_var('p', 1);
	$input['file']		= request_var('file', '');
	$input['s']		= request_var('s', 0);
	$input['itval']		= request_var('itval', 1);

	if ($input['t'] == 0 && $input['p'] == 1) {
		$input['s']	 = time();
	}

	$path = $phpbb_root_path . 'store/' . $input['file'];
	if(!file_exists($path)) {
		trigger_error($user->lang['GENERAL_ERROR'] . adm_back_link($module->u_action), E_USER_WARNING);
    }

	@include($path . "/config.php");
	if(empty($b_table)) {
		trigger_error($user->lang['GENERAL_ERROR'] . adm_back_link($module->u_action), E_USER_WARNING);
	}

	$tables = explode(',', $b_table);
	$data_file = $path . '/' . $tables[$input['t']] . '_' . $input['p'] . '.php';
	@include($data_file);
	// Process restore
	$rows = count($sql);
	if (!empty($sql_drop)) {$db->sql_query($sql_drop);}
	if (!empty($sql_create)) {$db->sql_query($sql_create);}
	for($i = 0; $i < $rows; $i++) {
		$db->sql_query($sql[$i]);
	}

	$tbcount = count($tables);
	if ($input['p'] >= $tb[$tables[$input['t']]]) { // Final piece of this table
		$input['t']++;
		if ($input['t'] >= $tbcount) { // Final table
			add_log('admin', 'LOG_DB_RESTORE');
			$message = $user->lang['RESTORE_COMPLETED_BY_TIME'] . time_spended($input['s']);
			trigger_error($message . '<br /><br /><a href="' . $module->u_action . '"> ' . $user->lang['BACK_TO_PREV'] . '</a>');
		}

		// Goto next table
		$u_next = $module->u_action . '&amp;action=submit&amp;restore=1&amp;s=' . $input['s'] . '&amp;t=' . $input['t'] . '&amp;p=1&amp;file=' . $input['file'] . '&amp;itval=' . $input['itval'];
		meta_refresh($input['itval'], $u_next);
		trigger_error($user->lang['RESTORE_TABLE_COMPLETED'] . $tables[$input['t'] - 1] . '<br /><br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
	}

	$input['p']++; // Next piece
	$u_next = $module->u_action . '&amp;action=submit&amp;restore=1&amp;s=' . $input['s'] . '&amp;t=' . $input['t'] . '&amp;p=' . $input['p'] . '&amp;file=' . $input['file'] . '&amp;itval=' . $input['itval'];
	meta_refresh($input['itval'], $u_next);
	trigger_error($user->lang['RESTORE_STEP_COMPLETED'] . restore_progress_info($tables[$input['t']], $tbcount, $input['t'], $tb[$tables[$input['t']]], $input['p'] - 1) . '<br /><a href="' . $u_next . '"> ' . $user->lang['GO_TO_NEXT'] . ' &raquo;</a>');
}

function gen_zip_archive($src_path, $archive_root, $archname){
	global $phpbb_root_path, $phpEx, $config;

	include($phpbb_root_path . 'includes/phpzip.inc.' . $phpEx);

	mkdeepdir($archive_root);

	$z = new PHPZip();
    $z->Zip($src_path, $archive_root . '/' . $archname);
}

function  delete_folder($input_path)
{
	if(!file_exists($input_path)) {
		return  false;
	}
	$pf=@opendir($input_path);
	while( $file = @readdir($pf)) {
		if ($file != '.' && $file != '..') {
			if(is_dir($input_path . '/' . $file)) {
				delete_folder($input_path . '/' . $file);
			} else {
				@unlink($input_path . '/' . $file);
			}
		}
	}
	@closedir($pf); 
	if (@rmdir($input_path)) {
		return  true;
	} else {
		return false;
	}
}

function update_config_filenum($p, $table, $backup_path){
	$file = $backup_path . "/config.php";
	$text = read_file_raw($file);
	$rep1 = "\$tb['" . $table . "']=0;";
	$rep2 = "\$tb['" . $table . "']=" . $p . ";";
	$text = str_replace($rep1, $rep2, $text);
	write_file_raw($file, $text);
}

function restore_progress_info($tbname,$tbnum,$tb,$pnum,$p){
	$table = ($tb+1) . '/' . $tbnum;
	$record=$p . '/' . $pnum;

	$str = 'Table Name&nbsp;:&nbsp;<b>' . $tbname . '</b><br />';
	$str .= 'Table&nbsp;:&nbsp;<b>' . $table . '</b><br />';
	$str .= 'File&nbsp;:&nbsp;<b>' . $record . '</b><br />';
	return $str;
}

function backup_progress_info($tbname,$tbnum,$tb,$rnum,$r){
	$table=($tb+1).'/'.$tbnum;
	$record=$r;
	if($rnum!=-1) {
		$record=$r.'/'.$rnum;
	}
	$str =  'Table Name&nbsp;:&nbsp;<b>' . $tbname . '</b><br />';
	$str .= 'Table&nbsp;:&nbsp;<b>' . $table . '</b><br />';
	$str .= 'Record&nbsp;:&nbsp;<b>' . $record . '</b><br />';
	return $str;
}

function get_table_fields($tbname){
	global $db;

	$sql = "SHOW FIELDS FROM `".$tbname."`";
	$result = $db->sql_query($sql);
	
	$f='';
	$dh='';
	while ($row = $db->sql_fetchrow($result))
	{
		if($f){ $dh=',';}
		$f .= $dh . '`' . $row['Field'] . '`';
    }
	return $f;
}

function get_table_autoincr_fields($tbname, $autofield){
	global $db;
	$sql = "SHOW FIELDS FROM `".$tbname."`";
	$result = $db->sql_query($sql);
	
	$i=0;
	$autof=",";
	$f='';

	while ($row = $db->sql_fetchrow($result))
	{
		$i++;
		if(strstr($autofield,",".$tbname.".".$row['Field'].","))
		{
			$autof.=$i.",";
	    }
		if($row['Extra']=='auto_increment')
		{
			$f=$row['Field'];
		}
    }
	$return_r['num']=$i;
	$return_r['autof']=$autof;
	$return_r['auf']=$f;
	return $return_r;
}

function get_table_structure($table,$strufour){
	global $db;

	$dump = '$sql_drop = "DROP TABLE IF EXISTS `' . $table . "`;\";\r\n";

	$db->sql_query("SET SQL_QUOTE_SHOW_CREATE=1;");
	$sql = "SHOW CREATE TABLE `$table`;";
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	if ($row)
	{
		$create=str_replace("\"","\\\"",$row['Create Table']);
		if($strufour) {
			$create=convert_to_mysql4($create);
		}
		$dump .= '$sql_create = "' . $create . "\";\r\n";
		return $dump;
	} else {
		return false;
	}
}

function convert_to_mysql4($query){
	$exp = "ENGINE=";
	if(!strstr($query,$exp)) {
		return $query;
	}
	$exp1 = " ";
	$r = explode($exp,$query);
	$r1 = explode($exp1,$r[1]);
	$returnquery = $r[0] . "TYPE=" . $r1[0];
	return $returnquery;
}

function get_table_charset($char){
	global $db;
	if(empty($char)) {
		return false;
	}
	$sql = 'SHOW COLLATION LIKE "' . $char . '"';
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	if ($row)
	{
		return $row['Charset'];
	} else {
		return false;
	}
}

function get_table_info($tbname){
	global $db;
	if(empty($tbname)) {
		return false;
	}
	$sql = 'SHOW TABLE STATUS LIKE "' . $tbname . '"';
	$result = $db->sql_query($sql);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);
	if ($row)
	{
		return $row;
	} else {
		return false;
	}
}


function time_spended($time){
	$duration = time()-$time;
	$t['m'] = round($duration/60);
	$t['s'] = $duration % 60;

	return $t['m'] . 'min ' . $t['s'] . 's';
}

function mkdeepdir($path)
{
    unset($subpath);
    $path_array = explode('/', $path);
    foreach($path_array AS $path_unit)
    {
        if($path_unit=='') continue;
        $subpath_array[] = $path_unit;
        $subpath = implode('/', $subpath_array);
        if(!is_dir($subpath))
        {
            @mkdir($subpath, 0777);
            $fp = @fopen($subpath. '/index.html', 'w');
            fclose($fp);
        }
    }
}

function write_file($file,$string){
	$string=stripSlashes($string);
	$file_path = substr($file, 0, strrpos($file, '/'));
	if ($file_path != '') {
		mkdeepdir($file_path);
	}
	if (!$fp = fopen($file, 'w')) {
		echo 'file open error'. $file_path;
		exit;
	}
	fputs($fp,$string); fclose($fp);
	chmod($file,0777);
}

function write_file_raw($filepath,$string){
	$fp=fopen($filepath,"w");
	fputs($fp,$string); fclose($fp);
	chmod($filepath,0777);
}

function read_file_raw($filepath){
	$filepath = trim($filepath);
	$htmlfp = fopen($filepath,"r");
	if(strstr($filepath, "://")) {
		while($data=@fread($htmlfp,500000)) {
			$string .= $data;
		}
	} else {
		$string = fread($htmlfp, filesize($filepath));
	}
	fclose($htmlfp);
	return $string;
}

function string_escape($str){
	$str=mysql_escape_string($str);
	$str=str_replace('\\\'','\'\'',$str);
	$str=str_replace("\\\\","\\\\\\\\",$str);
	$str=str_replace('$','\$',$str);
	return $str;
}

?>